<template>
  <div class="box-answer-index">
    <div class="answer">
      <!-- 左边答题区 -->
      <div class="left">
        <!-- 作答提示 -->
        <div class="answer-tips">
          <div class="tips">
            <p>提示：</p>
            <p>每道题作答后，点击 '确定' 按钮之后再进行下一题，否则答题不记录</p>
            <p>所有题目做大完成之后，点击'提交'按钮，以完成作答</p>
          </div>
          <!-- <div class="preview" @click="preview">整卷预览</div> -->
        </div>
        <!-- 题型提示 -->
        <div class="answer-type-tips">
          单选题（累计40题，合计100分，单选题20*2分，判断题10*3分，多选题10*3分）
          <div class="time">
            <img src="@/assets/img/time.png" alt="倒计时" />
            <span>还剩：{{ formatTime }}</span>
          </div>
        </div>
        <!-- 答题区 -->
        <div class="answer-area">
          <div class="single-question" v-if="currentQuestion.type == 1">
            <div class="question">{{ currentQuestion.title }}</div>

            <div class="options box-options" v-for="(item, index) in currentQuestion.question_option" :key="index">
              <el-radio v-model="you_selectedAnswer[questionIndex].option" :label="item.option" @input="selectOption">
                <span>{{ item.option }}. </span>
                <span style="font-size: 1rem">{{ item.content }}</span>
              </el-radio>
            </div>
          </div>
          <!-- 多选题 -->
          <div class="multiple-question box-options" v-if="currentQuestion.type == 2">
            <div class="question">{{ currentQuestion.title }}</div>

            <div class="options" v-for="(item, index) in currentQuestion.question_option" :key="index">
              <el-checkbox-group v-model="you_selectedAnswer[questionIndex].option" @change="selectOption">
                <el-checkbox :label="item.option">
                  <span>{{ item.option }}. </span>
                  <span style="font-size: 1rem">{{ item.content }}</span>
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <!-- 判断题 -->
          <div class="judge-question box-options" v-if="currentQuestion.type == 3">
            <div class="question">{{ currentQuestion.title }}</div>

            <div class="options" v-for="(item, index) in currentQuestion.question_option" :key="index">
              <el-radio v-model="you_selectedAnswer[questionIndex].option" :label="item.option" @input="selectOption">
                <span>{{ item.option }}. </span>
                <span style="font-size: 1rem">{{ item.content }}</span>
              </el-radio>
            </div>
          </div>
          <!-- 按钮 -->
          <div class="area-btn">
            <div class="box-btn">
              <div class="last btn" @click="last">上一题</div>
              <div class="confirm btn" @click="confirm">确认</div>
              <div class="next btn" @click="next">下一题</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右边答题卡 -->
      <div class="right">
        <div class="answer-sheet">
          <div class="btn-submit" @click="confirmSubmit">确认交卷</div>
          <div class="sheet-body">
            <p class="tips">
              点击答题卡题目序号，跳转到该题处，
              <br />
              <br />
              可修改答案!
            </p>
            <h2 style="text-align: left; margin-top: 10px; margin-bottom: 20px">答题卡</h2>
            <div class="sheet">
              <div class="single-question">
                <div class="question-type">单选题:</div>
                <div class="box-question">
                  <div
                    class="sheet-options"
                    :class="{ 'selected-sheet-options': selectedQuestionsIndex.includes(index) }"
                    v-for="index in singleLength"
                    :key="index"
                    @click="changeQuestion(index)"
                  >
                    {{ index }}
                  </div>
                </div>
              </div>
              <div class="multiple-question">
                <div class="question-type">多选题:</div>
                <div class="box-question">
                  <div
                    class="sheet-options"
                    :class="{ 'selected-sheet-options': selectedQuestionsIndex.includes(index + singleLength) }"
                    v-for="index in multipleLength"
                    :key="index"
                    @click="changeQuestion(index + singleLength)"
                  >
                    {{ index + singleLength }}
                  </div>
                </div>
              </div>
              <div class="judge-question">
                <div class="question-type">判断题:</div>
                <div class="box-question">
                  <div
                    class="sheet-options"
                    :class="{ 'selected-sheet-options': selectedQuestionsIndex.includes(index + multipleLength + singleLength) }"
                    v-for="index in judgeLength"
                    :key="index"
                    @click="changeQuestion(index + multipleLength + singleLength)"
                  >
                    {{ index + multipleLength + singleLength }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--时间到了 弹窗 -->
    <pop v-if="timeOver" :seconds="3" :content="'时间到停止作答！3秒后自动交卷'" :isCountDown="true" @onConfirm="popConfirm" />
    <!-- 最后一题作答完成 弹窗 -->
    <pop
      v-if="isEndOver"
      :content="'每题答完，必须点击‘确认’;\n\n修改答案，点击右侧答题卡;\n\n确认无误，点击交卷'"
      :height="'12.5rem'"
      :width="'18.75rem'"
      :btnText="'我已确认'"
      @onConfirm="endOverConfirm"
    />
  </div>
</template>

<script>
export default {
  computed: {
    formatTime() {
      return `${this.padNumber(this.minutes)}分${this.padNumber(this.seconds)}秒`
    }
  },
  data() {
    return {
      timer: '',
      minutes: 60,
      seconds: 0,
      timeOver: false, // 显示时间到了弹窗
      automaticSubmit: false, // 时间到了自动交卷

      you_choice: '', // 你的选择

      currentQuestion: {}, // 当前的题目
      questionList: [], // 题目列表
      questionIndex: 0, // 当前题目的下标

      selectedQuestionsIndex: [], // 已选择的问题下标
      you_selectedAnswer: [], // 已选择的答案

      isEndOver: false,

      fullscreenLoading: false,

      singleIndex: 0,
      multipleIndex: 0,
      judgeIndex: 0,

      singleLength: 0,
      multipleLength: 0,
      judgeLength: 0
    }
  },
  methods: {
    // 计时相关
    countdown(time, callback) {
      // 利用回调
      let timer = setInterval(() => {
        if (time === 0) {
          clearInterval(timer)
        } else {
          time -= 1
          callback(time)
        }
      }, 1000)
    },
    padNumber(num) {
      return num.toString().padStart(2, '0')
    },
    updateTimer() {
      if (this.minutes === 0 && this.seconds === 0) {
        clearInterval(this.timer)
        this.timeOver = true
        this.automaticSubmit = true
      } else {
        if (this.seconds === 0) {
          this.minutes -= 1
          this.seconds = 59
        } else {
          this.seconds -= 1
        }
      }
    },
    startCountdown() {
      this.timer = setInterval(this.updateTimer, 1000)
    },

    // 切换替换
    changeQuestion(index) {
      try {
        console.log('切换序号：', index)
        this.questionIndex = index - 1
        this.currentQuestion = this.questionList[index - 1]
        this.you_choice = this.you_selectedAnswer[index - 1].option
        console.log(this.questionIndex)
      } catch (error) {
        console.log('切换题目失败')
      }
    },

    // 选择答案
    selectOption(e) {
      const index = this.you_selectedAnswer.findIndex(obj => obj.id === this.currentQuestion.id)
      if (index !== -1) {
        // Array.isArray(e) ? e.join('') : e
        this.you_selectedAnswer[index].option = e
      } else {
        this.you_selectedAnswer.push({ id: this.currentQuestion.id, type: this.currentQuestion.type, option: e })
      }
    },

    // 上一题
    last() {
      if (this.questionIndex <= 0) {
        this.$message.error('已是第一题了')
        return
      }
      this.questionIndex -= 1

      this.currentQuestion = this.questionList[this.questionIndex]

      this.you_choice = this.you_selectedAnswer[this.questionIndex].option
    },
    // 确认
    confirm() {
      if (!this.you_selectedAnswer[this.questionIndex] || this.you_selectedAnswer[this.questionIndex].option == '') {
        this.$message.error('还未选答案，暂定可直接点击下一题')
        return
      }
      if (this.questionIndex + 1 >= this.questionList.length) {
        this.isEndOver = true
        this.selectedQuestionsIndex.push(this.questionIndex + 1)
        return
      }

      this.questionIndex += 1
      if (!this.selectedQuestionsIndex.includes(this.questionIndex)) {
        this.selectedQuestionsIndex.push(this.questionIndex)
      }
      this.you_choice = this.you_selectedAnswer[this.questionIndex] ? this.you_selectedAnswer[this.questionIndex].option : ''

      this.currentQuestion = this.questionList[this.questionIndex]
    },
    // 下一题
    next() {
      // const isExist = this.you_selectedAnswer.some(item => item.id == this.currentQuestion.id)
      // if (!isExist) this.you_selectedAnswer[this.questionIndex] = { id: this.currentQuestion.id, type: this.currentQuestion.type, option: '' }
      if (this.you_selectedAnswer[this.questionIndex].option != '') {
        if (!this.selectedQuestionsIndex.includes(this.questionIndex)) {
          this.selectedQuestionsIndex.push(this.questionIndex + 1)
        }
      }

      if (this.questionIndex + 1 >= this.questionList.length) {
        this.$message.error('已是最后一题了')
        return
      }
      this.questionIndex += 1
      this.currentQuestion = this.questionList[this.questionIndex]
      this.you_choice = this.you_selectedAnswer[this.questionIndex] ? this.you_selectedAnswer[this.questionIndex].option : ''
    },

    // 弹窗确认
    popConfirm() {
      this.timeOver = false
      this.confirmSubmit()
    },

    // 最后一题答了 之后的弹窗
    endOverConfirm() {
      this.isEndOver = false
    },

    // 结束预览
    preview() {
      this.$router.replace('/preview')
      localStorage.setItem('test-paper', JSON.stringify(this.questionList))
      localStorage.setItem('you_selectedAnswer', JSON.stringify(this.you_selectedAnswer))
    },

    // 确认交卷
    async confirmSubmit() {
      try {
        if (this.automaticSubmit) {
          // 时间一到直接交卷 不用询问
          console.log('时间已到，收笔哈,以为您自动交卷')
          // 评分等待
          const loading = this.$loading({
            lock: true,
            text: '试卷已提交，正在评分，请稍等',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // 同理
          this.you_selectedAnswer.forEach(item => {
            if (item.type == 2) {
              item.option = item.option.join('')
            }
          })
          let param = JSON.stringify(this.you_selectedAnswer)
          const { data: res } = await this.$api().score.all({ questionList: param })
          loading.close()
          this.$store.commit('score/updateScore', res.score)
          this.$store.commit('score/updateDetailList', res.detailList)
          // this.$router.replace({ name: 'score' })
          this.preview()
        } else {
          // 时间未到，来点提示
          let tips = ''
          if (this.you_selectedAnswer.length < this.questionList.length) {
            tips = '问题并未答全，是否确认提交?'
          } else {
            tips = '确认交卷'
          }

          this.$confirm(tips, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            callback: async action => {
              if (action === 'confirm') {
                // 评分等待
                const loading = this.$loading({
                  lock: true,
                  text: '试卷已提交，正在评分，请稍等',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.7)'
                })
                // 将多选题 由数组 转为 字符串
                this.you_selectedAnswer.forEach(item => {
                  if (item.type == 2) {
                    item.option = item.option.join('')
                  }
                })
                let param = JSON.stringify(this.you_selectedAnswer)
                const { data: res } = await this.$api().score.all({ questionList: param })
                loading.close()
                this.$store.commit('score/updateScore', res.score)
                this.$store.commit('score/updateDetailList', res.detailList)
                // this.$router.replace({ name: 'score' })
                this.preview()
              }
            }
          })
        }
      } catch (error) {
        this.$message.error('出错,请稍后再操作')
      } finally {
        // loading.close()
        // localStorage.removeItem('you_selectedAnswer')
        // localStorage.removeItem('test-paper')
      }
    },

    // 获取题目
    async fetchQuestionList() {
      const loading = this.$loading({
        lock: true,
        text: '题目加载中，请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        const { data: res1 } = await this.$api().question.list({ sourceId: 1, type: 1, limit: 20 })
        const { data: res2 } = await this.$api().question.list({ sourceId: 1, type: 2, limit: 10 })
        const { data: res3 } = await this.$api().question.list({ sourceId: 1, type: 3, limit: 10 })
        this.questionList.push(...res1.data[0].data)
        this.questionList.push(...res2.data[1].data)
        this.questionList.push(...res3.data[2].data)
      } catch (error) {
        this.$message.error('网络加载失败，请刷新重试')
      } finally {
        loading.close()
      }
    }
  },

  async created() {
    try {
      await this.fetchQuestionList()
      // const { data: res } = await this.$api().question.list({ sourceId: 1, type: 1 })
      // const allQuestions = res.data.map(category => category.data).flat()
      // this.questionList = allQuestions
      this.currentQuestion = this.questionList[this.questionIndex]

      this.singleLength = this.questionList.filter(item => item.type == 1).length
      this.multipleLength = this.questionList.filter(item => item.type == 2).length
      this.judgeLength = this.questionList.filter(item => item.type == 3).length

      this.questionList.forEach(item => {
        this.you_selectedAnswer.push({ id: item.id, option: '', type: item.type })
      })
      this.you_selectedAnswer.forEach(item => {
        if (item.type == 2) {
          item.option = []
        }
      })
      this.you_selectedAnswer = localStorage.getItem('you_selectedAnswer') ? JSON.parse(localStorage.getItem('you_selectedAnswer')) : this.you_selectedAnswer
      if (JSON.parse(localStorage.getItem('you_selectedAnswer'))) {
        for (let i = 0; i < this.questionList.length; i++) {
          if (this.you_selectedAnswer[i].option == '' || this.you_selectedAnswer[i].option.length < 1) {
            continue
          }
          this.selectedQuestionsIndex.push(i + 1)
        }
      }
    } catch (error) {
      console.log('错误：', error)
    }
  },

  mounted() {
    this.startCountdown()
  },
  beforeDestroy() {
    // clearInterval(this.timer)
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/global-style.scss';
@import '@/assets/css/global-var.scss';

.box-answer-index {
  background-color: #f6f7fb;
  height: 100vh;
  width: 100%;
}

.answer {
  display: flex;
  width: 70%;
  height: 37.5rem;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 1rem;

  .answer-tips {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .tips {
      text-align: left;
    }

    .preview {
      @include display-center;
      height: 2.8125rem;
      width: 5.5rem;
      color: #fff;
      background-color: $btn_blue;
      border-radius: 0.625rem;
      cursor: pointer;
    }
  }

  .answer-type-tips {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 0.625rem;
    width: 57.5rem;
    background-color: #e1edfe;
    border: 1px solid #4d76ed;
    text-align: left;
    height: 3.125rem;
    margin: 1.875rem 0 15px 0;
  }

  .time {
    @include display-center;
    width: 15.625rem;
    background-color: #4d76ed;
    color: #fff;
    height: 100%;

    img {
      height: 1.25rem;
      width: 1.25rem;
      margin-right: 0.625rem;
    }
  }

  .answer-area {
    height: 27.1875rem;
    width: 57.5rem;
    background-color: #fff;
    padding: 0 1.25rem;
  }

  .box-options {
    height: 80%;
    overflow-y: auto;
  }

  .question {
    display: flex;
    align-items: center;
    height: 5rem;
  }

  .options {
    text-align: left;
    margin-bottom: 2.5rem;
  }

  .area-btn {
    @include display-center;
    position: fixed;
    bottom: 0;
    left: 0;
    background-color: $background_gray;
    height: 5rem;
    // width: 100%;
    width: 57.5rem;

    .box-btn {
      display: flex;
    }

    .btn {
      @include display-center;
      width: 6.875rem;
      height: 2.8125rem;
      background: #fff;
      border: 1px solid $btn_blue;
      cursor: pointer;
    }

    .btn:nth-child(2) {
      margin: 0 1.25rem;
      background-color: $btn_blue;
      color: #fff;
    }
  }

  .answer-sheet {
    display: flex;
    flex-direction: column;
    width: 16.25rem;
    height: 25rem;
    background: #fff;
    margin: 0 0.625rem;

    .tips {
      color: $btn_red;
      font-size: 0.875rem;
      text-align: left;
    }
  }

  .btn-submit {
    @include display-center;
    height: 3.125rem;
    background-color: $btn_red;
    color: #fff;
    cursor: pointer;
  }

  .sheet-body {
    flex: 1;
    padding: 0.625rem;
    overflow-y: scroll;
  }

  .question-type {
    margin-bottom: 0.625rem;
  }

  .box-question {
    display: flex;
    flex-wrap: wrap;
  }

  .sheet-options {
    @include display-center;
    border-radius: 100%;
    border: 0.0625rem solid $background_gray;
    height: 1.875rem;
    width: 1.875rem;
    font-size: 0.875rem;
    margin: 0.5rem;
    cursor: pointer;
  }

  .selected-sheet-options {
    color: #fff;
    background-color: $btn_blue;
  }
}
</style>
